import React from 'react';
import Loading from '@/components/Loading';
import { Routes, Route, Navigate } from 'react-router-dom';
import routes from './routes';

const loadPage = (page: any, props = {}) => {
    if (page.element) {
        const StaticComp = page.element;
        return <StaticComp {...props} />;
    }

    if (page.url) {
        const LazyComp = React.lazy(() => import(/* @vite-ignore */ page.url));
        return (
            <React.Suspense fallback={<Loading />}>
                <LazyComp {...props} />
            </React.Suspense>
        );
    }

    if(page.items){
        return null;
    }

    return (
        <div className="p-4 w-100 text-center text-red-500">
            ⚠ 页面<span style={{ fontWeight: 'bolder', padding: '0 4px', color: '#eb081d'}}>({page.path})</span>组件未配置：请检查配置项是否缺少 <code>element</code> 或 <code>url</code>
        </div>
    );
}

type RouteProp = {
    path: string, 
    name?: string, 
    url?: string, 
    element?: any,
    children?: any[]
}

export default () => {
    const loadChildren = (children: any[], parentPath: string): React.ReactNode =>{
        parentPath = parentPath || '';
        if(!children.length) return null;
        return (
            <>
                {
                    children.map((item: RouteProp, itemIndex: number) => {
                        const _child_path = item.path || '';
                        const _child_element = loadPage(item, item);
                        
                        if(!_child_path && item.children){
                            return (
                                <>
                                    {
                                        loadChildren(item.children, parentPath)
                                    }
                                </>
                            );
                        }

                        const fullPath = `${parentPath.replace(/\/$/, '')}/${item.path.replace(/^\//, '')}`;
                        return (
                            <Route key={itemIndex} path={fullPath} element={_child_element} >
                                {
                                    item.children && loadChildren(item.children, fullPath)
                                }
                            </Route>
                        );
                    })
                }
            </>
        )
        
    }
    return (
        <Routes>
            <Route index element={<Navigate to="/root" replace />} />
            {
                routes.map((page, index) => {
                    const _element = loadPage(page, page);
                    return (
                        <Route key={index} path={page.path} element={_element} >
                            {
                                page.children && loadChildren(page.children, page.path)
                            }
                        </Route>
                    );
                })
            }
        </Routes>
    );
}